<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <div>
    <BasicDrawer
      v-bind="$attrs"
      :showFooter="true"
      :okAuth="'wms.wh:rd10:wmsRd10:edit'"
      @register="registerDrawer"
      @ok="handleSubmit"
      width="60%"
    >
      <template #title>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} {{ getTitle.djno ? ' | ' + getTitle.djno : '' }} </span>
        <!-- <DictLabel dictType="wms_rd10_status" :dictValue="getTitle.djStatus" defaultValue="1"/> -->
        <!-- <div class="flex" v-if="!getTitle.isNewRecord">
          <a-button primary @click="handleForm({})" v-auth="'wms.wh:rd10:wmsRd10:edit'"> <Icon icon="i-ant-design:printer-outlined" /> {{ t('产品标签') }} </a-button>
          <a-button primary @click="handleForm({})" v-auth="'wms.wh:rd10:wmsRd10:edit'"><Icon icon="i-ant-design:printer-outlined" /> {{ t('补打(产品)') }}</a-button>
          <a-button primary @click="handlePrintTray({})" v-auth="'wms.wh:rd10:wmsRd10:edit'"><Icon icon="i-ant-design:printer-outlined" /> {{ t('托盘码') }}</a-button>
        </div> -->
      </template>
      <BasicForm @register="registerForm" ref="basicFormModel">
        <template #cbatch="{ model, field }">
          <a-input-group compact>
            <a-input v-model:value="model['parent.cbatch']" style="width: calc(100% - 500px)" disabled="true" />
            <a-button type="primary" @click="handleCbatchPreview(model, field)" v-if="model['parent.cbatch'] == '1'">批次预览</a-button>
          </a-input-group>
        </template>
        <template #tuopaninfo="{ model, field }">
          <a-button type="primary" @click="handleBasInvPack(model, field)" v-auth="'wms.wh:rd10:wmsRd10:edit'" v-if="model.djStatus == '1'"> {{ t('选择包装规格') }} </a-button>
          <ListSelect
            ref="listSelectRef"
            selectType="basInvPackSelect"
            @select="handleSelect"
            :selectList="selectListRef"
            :queryParams="queryParams"
            v-show="false"
          />
        </template>
      </BasicForm>
      <!-- <template #appendFooter>
      </template> -->
      <template #footer>
          <!-- <BpmButton
          v-model:bpmEntity="record"
          bpmEntityKey="id"
          formKey="mf_rd10_nottify"
          completeText="发送通知"
          draftText="保存"
          :completeModal="true"
          :loading="loadingRef"
          :auth="'wms.wh:rd10:wmsRd10:edit'"
          @validate="handleValidate"
          @complete="handleSubmit"
          @success="handleSuccess"
          @close="closeDrawer"
        /> -->
    </template>
    </BasicDrawer>
    
  </div>
</template>
<script lang="ts" setup name="ViewsWmsWhRd10WmsRd10Form">
  import { ref, unref, computed, nextTick } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm, formModel } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { WmsRd10, wmsRd10Save, wmsRd10Form, wmsRd10CreateBatch } from '/@/api/wms/wh/rd10/wmsRd10';
  import { wmsRds10Form } from '/@/api/wms/wh/rd10/wmsRds10';
  import { BpmButton } from '/@/components/Bpm';
  import { basWarehousetreeData } from '/@/api/bas/house/basWarehouse';
  import { DictLabel } from '/@/components/Dict';
  import { officeTreeData } from '/@/api/sys/office';
  import { useGlobSetting } from '/@/hooks/setting';
  import { basInvPackListData } from '/@/api/bas/inv/pack/basInvPack';
  import { ListSelect } from '/@/components/ListSelect';
  import { NumEnum } from '/@/enums/defEnum';
  import { toNumberFixed } from '/@/utils/index';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wms/wh.rd10.wmsRds10');
  const { showMessage, createSuccessModal } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<WmsRds10>({} as WmsRds10);
  const loadingRef = ref(false);
  const showPrintDrawer = ref(false);
  //批次管理
  const binvbatch = ref<boolean>(true);
  // 换算率
  const bfixExch = ref<string>('');

  const basicFormModel = ref<any>(null);
// record.value.djno,
  
  const getTitle = computed(() => ({
    
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: t('入库明细'),
    djno: record.value.parentId,
    isNewRecord: record.value.isNewRecord,
  }));
  const selectListRef = ref<any>([]);
  let queryParams = ref< any >({});
  const listSelectRef = ref<any>(null);
  const inputFormSchemas: FormSchema[] = [
    {
      label: t('基本信息'),
      field: 'ddate1',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('单据日期'),
      field: 'parent.ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
      // 编辑时不允许修改
      dynamicDisabled: true,
    },
    {
      label: t('单据状态'),
      field: 'parent.djStatus',
      component: 'Select',
      componentProps: {
        dictType: 'wms_rd10_status',
        defaultValue: '1',
      },
      dynamicDisabled: true,
      ifShow: false,
    },
    {
      label: t('仓库编码'),
      field: 'parent.whCode',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('存货名称'),
      field: 'basInv.invName',
      fieldLabel: 'basInv.invName',
      component: 'ListSelect',
      componentProps: ({ tableAction, formModel }) => {
        return {
          selectType: 'whBasInvSelect',
          onSelect: (values) => {
            console.log(values);
            binvbatch.value = values[0].binvbatch == '1' ? true : false;
            bfixExch.value = values[0].bfixExch;
            formModel['basInv.invStd'] = values[0].invStd;
            formModel['basInv.unitName'] = values[0].unitName;
            formModel['invCode'] = values[0].invCode;
            formModel['packSize'] = '';
            formModel['pieceQty'] = '';
            formModel['packName'] = '';
          }
        }
      },
      dynamicDisabled: computed(() => !record.value.isNewRecord),
      required: true,
    },
    {
      label: t('存货编码'),
      field: 'invCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
      required: true,
    },
    {
      label: t('规格型号'),
      field: 'basInv.invStd',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('单位'),
      field: 'basInv.unitName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('货位名称'),
      field: 'basPos.posName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('货位编码'),
      field: 'basPos.posCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('件数'),
      field: 'inum',
      component: 'Input',
      componentProps: ({ formModel }) => {
        return {
          maxlength: 16,
          onBlur: (e) => {
            // formModel['ichangeRate'] ? formModel['iqty'] = (e.target.value * formModel['ichangeRate']).toFixed(NumEnum.scaleQty) : '';
            formModel['ichangeRate'] ? formModel['iqty'] = toNumberFixed(e.target.value * formModel['ichangeRate']) : '';
          },
        }
      },
      rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个整数') }],
      ifShow: computed(() => bfixExch.value == 0 ? false : true),
    },
    {
      label: t('含量(%)'),
      field: 'ichangeRate',
      component: 'Input',
      componentProps: ({ formModel }) => {
        return {
          maxlength: 16,
          onBlur: (e) => {
            // formModel['inum'] ? formModel['iqty'] = (formModel['inum'] * e.target.value).toFixed(NumEnum.scaleQty) : '';
            formModel['inum'] ? formModel['iqty'] = toNumberFixed(formModel['inum'] * e.target.value) : '';
          },
        }
      },
      // rules 只能保留两位小数
      rules: [{ required: true },{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d{0,2})?$/, message: t('请输入一个数值，保留两位小数') }],
      // binvbatch.value 为 0 时不显示该字段
      ifShow: computed(() => bfixExch.value == 0 ? false : true),
    },
    {
      label: t('入库数量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      // binvbatch.value 为 0 该字段可以手动输入
      // dynamicDisabled: computed(() => bfixExch.value == 0 ? false : true),
      dynamicDisabled: true,
      rules: [{ required: true }, { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(' '),
      field: 'white',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('检验员'),
      field: 'parent.checkBy',
      component: 'Select',
      componentProps: {
        dictType: 'mf_check_person',
        allowClear: true,
      },
      required: true,
      dynamicDisabled : true
    },
    {
      label: t('班次'),
      field: 'parent.teamClass',
      component: 'Select',
      componentProps: {
        dictType: 'mf_team_class',
        allowClear: true,
      },
      required: true,
      dynamicDisabled : true
    },
    {
      label: t('班组'),
      field: 'parent.cteam',
      component: 'Select',
      componentProps: {
        dictType: 'mf_team',
        allowClear: true,
      },
      required: true,
      dynamicDisabled : true
    },
    {
      label: t('品级'),
      field: 'parent.cgrade',
      component: 'Select',
      componentProps: {
        dictType: 'mf_grade',
        allowClear: true,
      },
      required: true,
      dynamicDisabled : true
    },

    {
      label: t('批次信息'),
      field: 'picinfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: () => binvbatch.value == true,
    },
    {
      label: t('批次'),
      field: 'parent.cbatch',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      colProps: { lg: 24, md: 24 },
      ifShow: () => binvbatch.value == true,
      slot: 'cbatch',
      dynamicDisabled: true,
    },
    {
      label: t('托盘信息'),
      field: 'tuopaninfo',
      component: 'FormGroup',
      colProps: { lg: 2, md: 24 },
    },
    {
      label: t(''),
      field: 'tuopaninfo1',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      colProps: { lg: 22, md: 24 },
      slot: 'tuopaninfo',
    },
    {
      label: t('包装名称'),
      field: 'parent.packName',
      component: 'Input',
      dynamicDisabled: true,
    },
    {
      label: t('托盘容量'),
      field: 'parent.packSize',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      dynamicDisabled: true,
    },
    {
      label: t('单件容量'),
      field: 'parent.pieceQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      dynamicDisabled: true,
    },

    {
      label: t('当前序号'),
      helpMessage: '当前已喷的最大序号',
      field: 'maxTpSeq',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
      dynamicDisabled: true,
    },
    {
      label: t('入库信息'),
      field: 'white',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('数量'),
      field: 'parent.iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      dynamicDisabled: true,
    },
    {
      label: t('件数'),
      field: 'parent.inum',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      ifShow: computed(() => bfixExch.value == 0 ? false : true),
      dynamicDisabled: true,
    },
    {
      label: t('剩余数量'),
      field: 'parent.syQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      dynamicDisabled: true,
    },
    {
      label: t('剩余件数'),
      field: 'parent.syNum',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      ifShow: computed(() => bfixExch.value == 0 ? false : true),
      dynamicDisabled: true,
    },

    {
      label: t('累计入库数量'),
      field: 'parent.sumQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      dynamicDisabled: true,
    },
    {
      label: t('累计入库件数'),
      field: 'parent.sumNum',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      ifShow: computed(() => bfixExch.value == 0 ? false : true),
      dynamicDisabled: true,
    },
    {
      label: t('制单人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      ifShow: false,
    },
    {
      label: t('修改人'),
      field: 'updateByName',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      ifShow: false,
    },
    
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getForm, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await wmsRds10Form(data);
    record.value = (res.wmsRds10 || {}) as WmsRd10;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      loadingRef.value = true;
      const data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      // data.status = record.value.status; // 提交状态
      data.status = 9; // 草稿状态
      data.djStatus = data.djStatus ? data.djStatus : 1;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      // console.log('submit', params, data, record);
      const res = await wmsRd10Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      setDrawerProps({ confirmLoading: false });
      record.value.isNewRecord = false;
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSubmit(event: any) {
    try {
      if(record.value.isNewRecord){
        showMessage('请先保存单据再发送通知！！');
        return;
      }
      loadingRef.value = true;
      const data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = 4; // 提交状态
      data.djStatus = data.djStatus ? data.djStatus : 1;
      console.log('data', data);
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      // console.log('submit', params, data, record);
      const res = await wmsRd10Save(params, data);
      showMessage(res.message);
      // setTimeout(closeDrawer);
      record.value.isNewRecord = false;
      setDrawerProps({ confirmLoading: false });
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleCbatchPreview(model: any, field: any) {
    // console.log(model, field, 'model, field===');
    if (!model.invCode) {
      showMessage('请选择存货！！');
      return;
    }
    if (!model.checkBy) {
      showMessage('请选择验收人！！');
      return;
    }
    if (!model.teamClass) {
      showMessage('请选择班次！！');
      return;
    }
    if (!model.cteam) {
      showMessage('请选择班组！！');
      return;
    }
    if (!model.cgrade) {
      showMessage('请选择品级！！');
      return;
    }
    console.log(model,'model===');
    // model.ddate M2 日期格式转换为 YYYY-MM-DD
    const ddate = model.ddate.$y + '-' + (model.ddate.$M + 1) + '-' + model.ddate.$D;
    const params = {
      invCode: model.invCode,
      checkBy: model.checkBy,
      teamClass: model.teamClass,
      cteam: model.cteam,
      cgrade: model.cgrade,
      ddate: ddate,
    }
    const res  = await wmsRd10CreateBatch(params);
    // 返回 cbatch
    model.cbatch = res.data.cbatch;
    record.value.cbatch = res.data.cbatch;
  }

  async function handleSuccess() {
    emit('success');
  }

  async function handleSelect(selectData) {
    await nextTick();
    // console.log(,'record.value===');
    const getFields = basicFormModel.value.getFieldsValue()
    const data = {
      ...getFields,
      packName: selectData[0]['packName'],
      pieceQty: selectData[0]['pieceQty'],
      packSize: selectData[0]['packSize'],
    }
    setFieldsValue(data);

  }

  async function handleBasInvPack(model: any, field: any) {
    console.log(model, field, 'model, field===',listSelectRef.value);
    if (!model.invCode) {
      showMessage('先请选择存货！！');
    }else{
      selectListRef.value = []
        queryParams.value = {
          invCode: model.invCode
        }
        setTimeout(()=>{
          listSelectRef.value.openSelectModal();
        })
    }   
  }

  function initialize(task: Recordable, bpm: Recordable) {
    console.log(task, 'task===', bpm);
  }
</script>
<style lang="less" scoped>
.jeesite-bpm-btns{
  width: auto !important;
}
.flex{
  margin-left: 20px;
  display: inline-block;
  button{
    margin-right: 20px;
    border: 1px solid #0096c7;
  }
}
</style>